<script setup lang="ts">
import { getBuyerDetailById } from "~/api/goods";
import { onMounted, ref } from "vue";
import { useUserStore } from "~/store/useUser";
import { useRouter } from "vue-router";
import { commitOrder, createOrder } from "~/api/order";
import { useOrderStore } from "~/store/useOrder";
import { useImageCache } from "~/composables/useImageCache";

// 支付类型枚举
enum PaymentType {
  Alipay = "ALIPAY",
  Wechat = "WECHAT",
}

useSeoMeta({
  title: "购买服务 - 技能猴子",
  ogTitle: "购买服务 - 技能猴子",
  description: "技能猴子，找技能服务，我喜欢和技能人才直接聊",
  ogDescription: "技能猴子，找技能服务，我喜欢和技能人才直接聊",
});

interface UserInfo {
  nickname: string;
  userId: string;
  userType: string;
  username: string; // username就是用户手机号
  // 添加其他必要的用户信息属性
}

const orderStore = useOrderStore();
const router = useRouter();
const userStore = useUserStore();
const userInfo = ref<UserInfo>({} as UserInfo);
const details = ref<any>({});
const selectedVersion = ref<"standard" | "experience">("standard");
const { getCoverImage } = useImageCache();

onMounted(() => {
  const query = useRoute().query;
  if (query.id) {
    getDetails(query.id as string);
  }
  if (query.ver) {
    selectedVersion.value = query.ver == 1 ? "standard" : "experience";
  }
  userInfo.value = userStore.getUserInfo;
  orderMobile.value = userInfo.value.username || ''; // username就是手机号

  // 打印用户信息
  console.log('用户信息:', userInfo.value);
  console.log('用户手机号(username):', userInfo.value.username);
  console.log('昵称:', userInfo.value.nickname);
  console.log('用户ID:', userInfo.value.userId);
  console.log('用户类型:', userInfo.value.userType);
  console.log('订单联系方式:', orderMobile.value);
});

const getDetails = async (id: string) => {
  try {
    const data = await getBuyerDetailById({ id });
    console.log('商品详情请求响应:', data);
    console.log('startServiceTimes字段值:', data.data?.startServiceTimes || data.data?.baseInfo?.startServiceTimes);

    if (data && data.data) {
      // 适配新的数据格式
      if (data.data.baseInfo) {
        // 旧数据格式，保持原有处理逻辑
        details.value = data.data;

        // 设置审核状态，确保购买按钮能够显示
        if (!details.value.baseInfo.auditStatus) {
          details.value.baseInfo.auditStatus = true;
        }
      } else if (data.data.id) {
        // 新数据格式，转换为旧格式结构
        details.value = {
          baseInfo: {
            id: data.data.id,
            goodsName: data.data.goodsName,
            goodsTypeName: data.data.typeName,
            // 处理coverPic可能是ID字符串的情况，并使用getCoverImage处理
            coverPic: data.data.coverPic ?
              (Array.isArray(data.data.coverPic) ? data.data.coverPic.map(pic => getCoverImage(pic)) : [getCoverImage(data.data.coverPic)]) :
              (data.data.goodsResources ? data.data.goodsResources.map(item => getCoverImage(item.mainPic || item.ossId)) : []),
            sysUserId: data.data.shopId,
            nickName: data.data.shopName || '未知用户',
            profile: data.data.shopProfile,
            score: data.data.score,
            commentCount: data.data.orderCount || 0,
            creditLevel: data.data.creditLevel,
            creditScore: data.data.creditScore,
            saleCount: data.data.saleCount,
            deliveryRate: data.data.deliveryRate,
            replyRate: data.data.replyRate,
            uimKey: data.data.shopId,
            isBond: data.data.isBond,
            shopAvatar: data.data.shopAvatar,
            bondAmount: data.data.bondAmount,
            startServiceTimes: data.data.startServiceTimes ?? 0, // 开启服务时间
            auditStatus: true  // 设置审核状态，确保购买按钮能够显示
          },
          introduce: {
            introduce: data.data.introduce || ''
          },
          labelList: (data.data.labels || '').split(',').map(label => ({ label }))
        };

        // 处理商品规格数据
        if (data.data.goodsSpecifications && data.data.goodsSpecifications.length > 0) {
          // 标准版 - 优先根据skuType识别，如果没有skuType=1的，则使用isDefault=1的
          const standardSpec = data.data.goodsSpecifications.find(spec => spec.skuType === 1) || 
                               data.data.goodsSpecifications.find(spec => spec.isDefault === 1);
          if (standardSpec) {
            details.value.standard = {
              id: standardSpec.id,
              goodsAmount: standardSpec.goodsAmount,
              deliverDays: standardSpec.deliverDays,
              introduce: standardSpec.skuName,
              detailsServer: standardSpec.features?.map(feature => ({
                content: typeof feature === 'object' ? feature.content : feature
              })) || []
            };
          }

          // 体验版 - 根据skuType=2识别
          const trialSpec = data.data.goodsSpecifications.find(spec => spec.skuType === 2);
          if (trialSpec) {
            details.value.experience = {
              id: trialSpec.id,
              goodsAmount: trialSpec.goodsAmount,
              deliverDays: trialSpec.deliverDays,
              introduce: trialSpec.skuName,
              detailsServer: trialSpec.features?.map(feature => ({
                content: typeof feature === 'object' ? feature.content : feature
              })) || []
            };
          }
          
          console.log('buyGoods页面处理SKU数据:', {
            totalSpecs: data.data.goodsSpecifications.length,
            standardSpec: standardSpec ? { id: standardSpec.id, skuType: standardSpec.skuType, isDefault: standardSpec.isDefault } : null,
            trialSpec: trialSpec ? { id: trialSpec.id, skuType: trialSpec.skuType, isDefault: trialSpec.isDefault } : null,
            hasStandard: !!details.value.standard,
            hasExperience: !!details.value.experience
          });
        }

        // 处理资源数据
        details.value.audioResources = data.data.audioResources || [];
        details.value.videoResources = data.data.videoResources || [];
        details.value.imageResources = data.data.imageResources || [];
        details.value.documentResources = data.data.documentResources || [];
      }
      console.log('设置商品详情数据成功');
    } else {
      console.error('商品详情数据格式不正确:', data);
    }
  } catch (e) {
    console.error('获取商品详情失败', e);
  } finally {
    console.log('最终details数据:', details.value);
    console.log('startServiceTimes最终值:', details.value.baseInfo?.startServiceTimes);
  }
};

const updateContactDialog = ref(false);
const serviceSpecificationsDialog = ref(false);
const editContact = () => {
  updateContactDialog.value = true;
};
const editSelectService = () => {
  if (!details.value.experience) {
    return ElMessage.info("该商品只有标准版");
  }
  serviceSpecificationsDialog.value = true;
};

const getSelectedVersionDetails = () => {
  if (!details.value) {
    return { goodsAmount: 0, deliverDays: 0, introduce: '', detailsServer: [] };
  }
  const versionDetails = selectedVersion.value === "standard"
    ? details.value.standard
    : details.value.experience;

  return versionDetails || { goodsAmount: 0, deliverDays: 0, introduce: '', detailsServer: [] };
};

const formatPrice = (price: number | undefined | null) => {
  if (price === undefined || price === null || isNaN(Number(price))) {
    return '0.00';
  }
  return `${Number(price).toFixed(2)}`;
};
// 创建订单
const remark = ref("");
const orderMobile = ref("");
const createLoading = ref(false);
const createOrderHandle = async () => {
  createLoading.value = true;
  try {
    // 打印当前用户信息
    console.log('创建订单时的用户信息:', {
      userInfo: userInfo.value,
      orderMobile: orderMobile.value,
      selectedVersion: selectedVersion.value,
      remark: remark.value
    });

    // 第一步：提交订单获取订单ID
    const orderData = {
      goodsId: details.value.baseInfo.id,
      orderMobile: orderMobile.value,
      remark: remark.value,
      skuType: selectedVersion.value === "standard" ? 1 : 2,
    };

    console.log('提交订单数据:', orderData);
    const orderResult = await commitOrder(orderData);
    console.log('订单提交结果:', orderResult);

    // 根据新的接口返回格式，订单编号可能在 data 或 msg 字段中
    const orderSn = orderResult.data || orderResult.msg;
    
    if (!orderSn) {
      throw new Error('订单创建失败，未获取到订单编号');
    }

    // 跳转到支付页面，并传递订单编号和商品ID
    router.push(`/pay?orderSn=${orderSn}&gid=${details.value.baseInfo.id}`);
  } catch (e) {
    console.error('创建订单失败:', e);
    // 检查是否是接口返回的错误信息
    let errorMessage = '创建订单失败，请稍后重试';
    if (e.response && e.response.data && e.response.data.msg) {
      errorMessage = e.response.data.msg;
    } else if (e.message) {
      errorMessage = e.message;
    }
    ElMessage.error(errorMessage);
  } finally {
    createLoading.value = false;
  }
};
// 开启服务时间
const startTime = computed(() => {
  const timeType = details.value.baseInfo.startServiceTimes;
  switch (timeType) {
    case 0:
      return "24小时内";
    case 1:
      return "3天内";
    case 2:
      return "7天内";
    case 3:
      return "任何时候";
  }
  return "立刻";
});
//
const updateContactConfirm = (value: string) => {
  orderMobile.value = value;
  updateContactDialog.value = false;

  // 打印更新后的联系方式
  console.log('联系方式已更新:', value);
  console.log('当前订单联系方式:', orderMobile.value);
};
//
const remarkInput = (e: any) => {
  if (e.target.value.length > 200) {
    ElMessage.warning("备注不能超过200字");
    e.target.value = e.target.value.slice(0, 199);
    return;
  }
  remark.value = e.target.value;
};
</script>

<template>
  <div>
    <BaseHeaderMenuWhite bg-color="white" />
    <div class="body">
      <div class="box">
        <div class="body-left">
          <h4 class="title">购买服务</h4>
          <div class="contact">
            <p>
              <span>你的联系方式 </span
              ><span>{{ orderMobile || userInfo.username }}</span>
            </p>
            <!-- <span class="edit" @click="editContact"
              ><img src="~/assets/edit-icon.png" alt="" />修改</span
            > -->
          </div>
          <div class="goods-info" v-if="details.baseInfo">
            <div class="goods-head">
              <img class="goods-img" :src="getCoverImage(details.baseInfo.coverPic[0])" alt="" />
              <div class="info">
                <h4>{{ details.baseInfo.goodsName }}</h4>
                <p>
                  <span>好评率：{{ details.baseInfo.goodsCommentRate || 0 }}%</span>
                  <span
                    ><b>¥</b
                    >{{ formatPrice(getSelectedVersionDetails().goodsAmount) }}</span
                  >
                </p>
              </div>
            </div>
            <div class="type">
              <p>
                <span>购买的服务：</span
                >{{ selectedVersion === "standard" ? "标准版" : "体验版" }}
              </p>
              <span class="edit" @click="editSelectService"
                ><img src="~/assets/edit-icon.png" alt="" />修改</span
              >
            </div>
            <div class="service-list">
              <p
                v-for="item in getSelectedVersionDetails().detailsServer.filter((item: any) => item.content)"
                :key="item.id"
              >
                <img src="~/assets/checked-icon.png" alt="" /><span>{{
                  item.content
                }}</span>
              </p>
            </div>
            <p class="jf">
              <span>交付周期</span>
              <span>{{ getSelectedVersionDetails().deliverDays }}天</span>
            </p>
            <p class="jf">
              <span>开启时间</span>
              <span>现在下单，{{ startTime }}开启服务</span>
            </p>
            <p class="jf">
              <span>备注 <i>（选填）</i></span>
            </p>
            <p class="textarea">
              <textarea
                v-model="remark"
                placeholder="您可以对最终交付内容做详细的描述，让最终的交付物更符合您的预期。"
                @input="remarkInput"
              ></textarea>
              <span class="textarea-count">{{ remark.length }}/200</span>
            </p>
          </div>
        </div>
        <div class="body-right">
          <h4 class="title">订单金额</h4>
          <div class="goods-info" v-if="details.baseInfo">
            <div class="goods-head">
              <img class="goods-img" :src="getCoverImage(details.baseInfo.coverPic[0])" alt="" />
              <div class="info">
                <h4>{{ details.baseInfo.goodsName }}</h4>
                <div class="user">
                  <div class="head">
                    <img :src="getCoverImage(details.baseInfo.shopAvatar)" alt="" />
                    <span></span>
                  </div>
                  <span class="name">{{ details.baseInfo.nickName }}</span>
                  <span class="lv">Lv.{{ details.baseInfo.creditLevel }}</span>
                </div>
              </div>
            </div>
            <p class="price">
              <span>单价</span>
              <span>￥{{ formatPrice(getSelectedVersionDetails().goodsAmount) }}</span>
            </p>
            <p class="price">
              <span>数量（份）</span>
              <span style="color: #191e28">x1</span>
            </p>
            <p class="count">
              合计：<span
                >￥{{ formatPrice(getSelectedVersionDetails().goodsAmount) }}</span
              >
            </p>
            <el-button
              :disabled="createLoading"
              class="submit-order"
              @click="createOrderHandle"
              :loading="createLoading"
            >
              提交订单
            </el-button>
            <p class="tips">资金安全 · 准时开启 · 按约交付 · 平台保障</p>
          </div>
        </div>
      </div>
    </div>
    <BaseFooter />
    <!-- 更新联系方式	-->
    <DialogUpdateContact
      v-if="updateContactDialog"
      :orderDetails="details"
      @closeDialog="updateContactDialog = false"
      @confirm="updateContactConfirm"
    />
    <!-- 选择服务规格	-->
    <DialogServiceSpecifications
      v-if="serviceSpecificationsDialog && details.standard && details.experience"
      @closeDialog="serviceSpecificationsDialog = false"
      :standard="details.standard"
      :experience="details.experience"
      :selectedVersion="selectedVersion"
      :startServiceTimes="details.baseInfo.startServiceTimes"
      @update:selectedVersion="selectedVersion = $event"
    />
  </div>
</template>

<style scoped lang="scss">
.body {
  background: #f9f9f9;
  padding-top: 80px;
  min-height: 100vh;
  box-sizing: border-box;
}
.box {
  width: 1100px;
  margin: 0 auto;
  display: flex;
  padding-top: 32px;
  padding-bottom: 36px;
}
.body-left {
  flex: 1;
  .title {
    color: #191e28;
    font-size: 20px;
    margin-bottom: 16px;
  }
  .contact {
    border-radius: 16px 16px 16px 16px;
    border: 1px solid rgba(25, 30, 40, 0.08);
    background: #ffffff;
    padding: 20px 24px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    p {
      flex: 1;
      span:nth-child(1) {
        color: #191e28;
        padding-right: 12px;
      }
      span:nth-child(2) {
        color: #1dbf73;
      }
    }
    .edit {
      color: #1dbf73;
      cursor: pointer;
      display: flex;
      align-items: center;
      img {
        width: 16px;
        height: 16px;
        margin-right: 4px;
      }
    }
  }
}
.goods-info {
  border-radius: 16px 16px 16px 16px;
  border: 1px solid rgba(25, 30, 40, 0.08);
  background: #ffffff;
  padding: 20px 24px;
  .goods-head {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    .goods-img {
      width: 120px;
      height: 76px;
      margin-right: 12px;
      cursor: pointer;
      border-radius: 8px;
    }
    .info {
      flex: 1;
      h4 {
        font-size: 15px;
        color: #191e28;
        margin-bottom: 12px;
        cursor: pointer;
      }
      p {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
        span:nth-child(1) {
          flex: 1;
          font-size: 12px;
          color: rgba(25, 30, 40, 0.6);
        }
        span {
          color: #ff4f4f;
          font-size: 22px;
          font-weight: bold;
          b {
            font-size: 14px;
          }
        }
      }
    }
  }
  .type {
    display: flex;
    align-items: center;
    p {
      color: #191e28;
      font-size: 16px;
      margin-right: 16px;
      span {
        font-weight: bold;
      }
    }
    .edit {
      display: flex;
      align-items: center;
      color: #1dbf73;
      cursor: pointer;
      img {
        width: 16px;
        height: 16px;
        margin-right: 4px;
      }
    }
  }
  .service-list {
    margin: 16px 0;
    background: rgba(25, 30, 40, 0.02);
    border-radius: 12px 12px 12px 12px;
    padding: 20px;
    box-sizing: border-box;
    p {
      display: flex;
      align-items: center;
      margin-bottom: 8px;
      line-height: 24px;
      &:last-child {
        margin-bottom: 0;
      }
      img {
        width: 15px;
        height: 15px;
        margin-right: 5px;
      }
    }
  }
  .jf {
    display: flex;
    align-items: center;
    line-height: 24px;
    margin-bottom: 12px;
    color: #191e28;
    font-size: 16px;
    span:nth-child(1) {
      flex: 1;
      font-weight: bold;
      i {
        font-style: normal;
        color: rgba(25, 30, 40, 0.48);
      }
    }
  }
  .textarea {
    height: 140px;
    position: relative;
    textarea {
      width: 100%;
      height: 100%;
      resize: none;
      background: rgba(25, 30, 40, 0.02);

      border-radius: 12px 12px 12px 12px;
      border: 1px solid rgba(25, 30, 40, 0.08);
      outline: none;
      padding: 12px 16px;
      box-sizing: border-box;
    }
    .textarea-count {
      position: absolute;
      bottom: 12px;
      right: 16px;
      color: rgba(25, 30, 40, 0.48);
      font-size: 12px;
    }
  }
}
.body-right {
  flex: 0 0 382px;
  margin-left: 24px;
  .title {
    margin-bottom: 16px;
    font-size: 20px;
  }
  .goods-info {
    .goods-head {
      h4 {
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: normal; /* 或者使用 nowrap，但这里使用 normal 以支持多行 */
        margin-bottom: 6px;
      }
      .user {
        display: flex;
        align-items: center;
        .head {
          width: 24px;
          height: 24px;
          position: relative;
          margin-right: 6px;
          img {
            width: 100%;
            height: 100%;
            border-radius: 100%;
          }
          span {
            position: absolute;
            bottom: -2px;
            right: 0;
            width: 10px;
            height: 10px;
            background: #1dbf73;
            border-radius: 100%;
            border: 2px solid #ffffff;
            box-sizing: border-box;
          }
        }
        .name {
          color: rgba(25, 30, 40, 0.72);
          padding-right: 4px;
        }
        .lv {
          color: #1dbf73;
          font-size: 12px;
        }
      }
    }
  }
  .price {
    display: flex;
    align-items: center;
    line-height: 24px;
    margin-bottom: 16px;
    span:nth-child(1) {
      flex: 1;
      font-weight: bold;
      font-size: 16px;
    }
    span:nth-child(2) {
      font-size: 16px;
      font-weight: bold;
      color: #ff4f4f;
    }
  }
  .count {
    text-align: right;
    padding: 20px 0 22px;
    border-top: 1px solid #ededee;
    font-size: 16px;
    color: rgba(25, 30, 40, 0.6);
    span {
      font-weight: bold;
      font-size: 22px;
      color: #ff4f4f;
      b {
        font-size: 16px;
      }
    }
  }
  .submit-order {
    width: 100%;
    height: 48px;
    background: #1dbf73;
    border-radius: 8px 8px 8px 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    color: #fff;
    font-weight: bold;
    margin-bottom: 16px;
    cursor: pointer;
    border: none;
  }
  .tips {
    text-align: center;
    color: rgba(25, 30, 40, 0.6);
    line-height: 24px;
  }
}
</style>
